import React, { useEffect, useState, useRef } from 'react'
import { List, Avatar, Image, Row, Col, message, Button, Typography, Modal, Input, Drawer,InputNumber, Table, Tag, Space, Tooltip, Popconfirm } from 'antd';
import axios from 'axios';
import { QuestionCircleTwoTone } from '@ant-design/icons';
import GoodsCascader from '../../../../components/GoodsCascader'
import { Navigate, useNavigate } from 'react-router-dom'
import moment from 'moment'
const loginUser = JSON.parse(localStorage.getItem("loginUser"));
const { Text } = Typography
export default function Index() {
    const navigate = useNavigate()
    const [listData, setListData] = useState([]);
   
    const [writeModal, setWriteModal] = useState(false)
    const [doTransformInfo, setDoTransformInfo] = useState();  //保存捐赠的物流信息
    const myExpressId = useRef();
    useEffect(async () => {
        const resp = await axios.get("http://localhost:8080/qryMyDonation?userid=" + loginUser.id)
        console.log(resp);
        setListData(resp.data.data)
        return () => {
        };
    }, []);

    const cancelDo=async (doid)=>{
        console.log("要取消的捐赠的id是", doid);
        const resp =  await axios.post("http://localhost:8080/cancelDo?doid=" + doid)
        if (resp.data.state =="0") {
            message.success(resp.data.message)
            setTimeout(() => {
                navigate('/userMenu/*')
                window.location.reload();
            }, 500);
        }
    }
   
    const showWriteModal = (record) => { //填写物流订单modal
        setWriteModal(true)
        setDoTransformInfo(record)
    }
    const writeModalOK = () => {
        //填写我的物流单号
        let rs = doTransformInfo;
        rs.doexpress = myExpressId.current.state.value
        setDoTransformInfo(rs)
        console.log(doTransformInfo);
        axios.post("http://localhost:8080/saveDoTransform", doTransformInfo).then(resp => {
            console.log(resp);
            if (resp.data.state === "0") {
                message.success(resp.data.message, 1)
                setWriteModal(false);
                setTimeout(() => {
                    window.location.reload()
                }, 800);
            } else {
                message.error(resp.data.message, 1)
                setWriteModal(false);
                setTimeout(() => {
                    window.location.reload()
                }, 800);
            }
        }).catch(err => {
            message.error("网络异常!", 1);
            setWriteModal(false);
            setTimeout(() => {
                navigate('/userMenu/*')
                window.location.reload()
            }, 800);
        })

    }
    const showDetailGoods = (record) => {
        console.log(record);
        Modal.info({
            title: '捐赠信息',
            content: <Row>
                {record.dotetail.map((item, index) => {
                    return <Tag color="green">{item.goodsname}X{item.goodsnum}</Tag>
                })}
            </Row>,
    
        });
    }
    const columns = [
        {
            title: '机构名称',
            key: 'orgname',
            render: (text, record) => (
                <Row align='middle'>
                    <Col span={8}>
                        <Avatar size={'large'} src={`http://localhost:8080/getOrgHead?id=${record.orgid}`} />
                    </Col>
                    <Col>{record.orgname}</Col>
                </Row>
            ),
        },
        {
            title: <Tooltip title="点击查看详情">我的捐赠 <QuestionCircleTwoTone /></Tooltip>,
            key: 'myDoList',
            ellipsis: true,
            render: (text, record) => (
                <Space onClick={() => { showDetailGoods(record) }}>
                  {record.dotetail.map((item, index) => {
                    return <Tag color="green">{item.goodsname}X{item.goodsnum}</Tag>
                  })}
                </Space>
              ),
        },

        {

            title: <Tooltip title="物品数量正确将获得一下积分,如有误机构将修改积分值">
                <span>预计积分 </span>
                <QuestionCircleTwoTone />
            </Tooltip>,
            key: 'point',
            render: (text, record) => (
                <Text type="secondary">{record.point}</Text>
            ),
        },
        {
            title:"时间",
            key:"dotime",
            sorter: (a, b) => Number(a.createtime) - Number(b.createtime),
            render:(text,record)=>(
                <span>{moment(Number(record.createtime)).format('YYYY-MM-DD HH:mm:ss')}</span>
            )
        },
        {
            title: '状态',
            key: 'dostate',
            render: (text, record) => (
                <Space size="middle">
                    {
                        <>
                            <Text code>{record.dostate == "0" ? "请填写物流" : record.dostate == "1" ? "等待机构审批" : record.dostate == "2" ? "已完成" : "已取消"}</Text>
                            {
                                record.dostate == "0" || record.dostate == "1" ? <Button type="primary" size="small" onClick={() => { showWriteModal(record) }}>填写</Button> : ""
                            }

                        </>
                    }
                </Space>
            ),
            filters: [
                {
                  text: '未填写物流',
                  value: '0',
                },
                {
                  text: '等待审批',
                  value: '1',
                },
                {
                    text: '已完成',
                    value: '2',
                },
                {
                    text: '已取消',
                    value: '3',
                }
            ],
         onFilter: (value, record) => record.dostate === value,
        },
        {
            title: 'Action',
            key: 'action',
            render: (text, record) => (
                <Space size="middle">
                    {
                        record.dostate == 0 || record.dostate == 1 ?
                            <Popconfirm
                                title="取消本次捐赠?"
                                onConfirm={() => {cancelDo(record.doid)}}
                                okText="Yes"
                                cancelText="No"

                            >
                                <Button type="primary" size="small" danger >取消</Button>
                            </Popconfirm> :
                            <></>
                    }
                    {
                      record.dostate == 0 || record.dostate == 1 ?
                      <Button type="primary" size="small" onClick ={() => {editDo(record)}}>修改数量</Button>:<></>
                    }

                </Space>
            ),
        },

    ];
    const editDo = (record) => {
        console.log(record);
        let donationRs = {doid:record.doid,goods:[]};
        Modal.confirm({
            title: '修改数量',
            content: <>
                {
                    record.dotetail.map((item,index)=>{
                        return (
                            <Row align="middle" justify="space-between" style={{width:'80%',margin: '0 auto',marginBottom:10}}>
                              <Col>
                                <Tag color="green">{item.goodsname}</Tag>
                              </Col>
                              <Col>
                                <InputNumber min={0} max={100} controls={false}
                                  onChange={(value) => {
                                    if ( donationRs.goods.length==0 ) {
                                      donationRs.goods.push({ "goodsname": item.goodsname, "goodsnum": value.eventPhase })
                                    }
                                      for (let i = 0; i < donationRs.goods.length; i++) {
                                        if (donationRs.goods[i].goodsname ==item.goodsname) {
                                          donationRs.goods[i].goodsnum = value;
                                        }else{
                                          if (i ==donationRs.goods.length-1) {
                                            donationRs.goods.push({ "goodsname": item.goodsname, "goodsnum": value })
                                          }
                                        }
                                      }
                                  }
                                  }
                                />
                              </Col>
                            </Row>
              
                          )
                    })
                }
            </>,
            onOk() {
                console.log(donationRs);
                // let params = {id:record.id,userid:record.userid,giftId:record.giftid};
                // console.log("取消礼物兑换:",params);
                // axios.post("http://localhost:8080/cancelGiftBuy",params).then(resp => {
               
                // })
                if (donationRs.goods.length>0) {
                    axios.post("http://localhost:8080/editDo",donationRs).then(resp=>{
                        if (resp.data.state === "0") {
                            message.success(resp.data.message, 1);
                            setTimeout(() => {
                                window.location.reload()
                            }, 500);
                        } else {
                            message.error(resp.data.message, 1)
                        }
                    })
                }
                
            },
        });
    }

    return (
        <div sylte={{ displayl: 'flex' }} className="animate__animated animate__fadeIn">
            <Table dataSource={listData} columns={columns} />
            <Modal
                title="修改"
                visible={writeModal}
                onCancel={() => { setWriteModal(false) }}
                onOk={writeModalOK}
            >
                <Input ref={myExpressId} />
            </Modal>
        </div>
    )
}
